//
//  SHNewfeatureViewController.swift
//  SHWeibo
//
//  Created by jingming wang on 16/7/26.
//  Copyright © 2016年 cpy.name. All rights reserved.
//

import UIKit

// cell 重用标识
private let identifier: String = "newFeatureCell"
class SHNewfeatureViewController: UICollectionViewController {
    //创建一个flowLayout
    let layout: UICollectionViewFlowLayout
    //重载初始化方法
    init() {
        layout = UICollectionViewFlowLayout()
        
        super.init(collectionViewLayout: layout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: - 设置界面
    private func setupUI() {
        layout.itemSize = CGSizeMake(K_SCREEN_WIDTH, K_SCREEN_HEIGHT)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .Horizontal
        
        collectionView?.backgroundColor = RandomColor()
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 注册cell
        collectionView?.registerClass(SHNewfeatureViewCell.self, forCellWithReuseIdentifier: identifier)
    }
}

extension SHNewfeatureViewController {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 4
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! SHNewfeatureViewCell
        cell.index = indexPath.item
        
        return cell
    }
    
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let index = Int(scrollView.contentOffset.x / K_SCREEN_WIDTH)
        // 代表最后一个cell
        if index == 3 {
            let cell = self.collectionView!.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! SHNewfeatureViewCell
            
            cell.closure = {
                // 发送通知 告知appdelegate 切换根控制器
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNoti, object: "newFeature")
            }
            // 开始动画
            cell.startAnimating()
        }
    }
}
